<template>
  <div class="user-list">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 布局 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 输入框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialog = !addDialog">添加用户</el-button>

          <!-- 对话框组件 -->
          <el-dialog title="添加用户" :visible.sync="addDialog" width="50%" @close="resetAddForm">
            <!-- 表单组件 -->
            <!-- 添加用户弹框 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
              <el-form-item label="账号" prop="username">
                <el-input v-model="addForm.username"></el-input>
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password"></el-input>
              </el-form-item>

              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
              </el-form-item>

              <el-form-item label="手机" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialog = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scoped">
            <!-- {{scoped.row}} -->
            <el-switch
              v-model="scoped.row.mg_state"
              active-color="#13ce66"
              inactive-color="#C0CCDA"
              @change="
                changeState(scoped.row.id, scoped.row.mg_state, scoped.row)
              "
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scoped">
            <!-- 编辑用户 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="getUserById(scoped.row.id)"
            ></el-button>
            <!-- 删除用户 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUser(scoped.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 编辑弹框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialog" width="50%">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUserById">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 校验邮箱
    let checkEmail = (rule, value, callback) => {
      // rule 校验规则
      // value 用户在input中输入的值
      // callback 回调函数 无论成功还是失败都要调用
      if (!value) return callback(new Error("请输入您的邮箱"));

      // 邮箱的正则校验
      if (
        /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(
          value
        )
      ) {
        //
        callback();
      } else {
        callback(new Error("您的邮箱格式不正确"));
      }
    };

    return {
      //查询
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      // 数据的总条数
      total: 0,
      // 用户列表
      userList: [],
      // 控制添加用户弹出框
      addDialog: false,
      //添加用户的数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 修改信息弹出框
      editDialog: false,
      // 编辑信息的数据
      editForm: {
        username: "",
        email: "",
        mobile: ""
      },
      // 根据接口文档  数据可以为空 那么就不需要校验 但是我们人为的认为不能为空 可删可不删
      editFormRules: {
        email: [
          { required: true, message: "请输入您的邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入您的手机号", trigger: "blur" }
        ]
      },
      //添加用户的表单校验
      addFormRules: {
        username: [
          { required: true, message: "请输入您的用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入您的密码", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入您的邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入您的手机号", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    //获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      // console.log(res);
      //如果没有成功 提示一下用户
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败!");

      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 处理 每页显示多少条数据
    handleSizeChange(size) {
      // 把size传给pagesize
      this.queryInfo.pagesize = size;
      this.getUserList();
    },
    // 跳转到第几页 要把页码要传出来
    handleCurrentChange(num) {
      this.queryInfo.pagenum = num;
      this.getUserList();
    },
    //改变用户状态
    async changeState(id, type, user) {
      // 发起ajax请求
      const { data: res } = await this.$http.put(`users/${id}/state/${type}`);
      // 如果更改用户状态失败 那么 把页码上的用户状态额值返回到以前的状态
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state;

        return this.$message.error("用户状态设置失败");
      }
    },
    //不管是点击关闭 还是取消 反正只要对话框关闭 就重置表单
    resetAddForm() {
      // console.log(111);
      this.$refs.addFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        //如果校验失败 直接return
        if (!valid) return;

        // 发起ajax请求
        const { data: res } = await this.$http.post("users", this.addForm);

        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error("用户添加失败");

        // 关闭弹出框
        this.addDialog = false;
        // 刷新页面
        this.getUserList();
      });
    },
    async removeUser(id) {
      const result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        return "cancel";
      });

      // console.log(result);

      // 如果用户选择了取消 那么 告诉用户 你取消了删除
      if (result === "cancel") {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
        // 如果用户选择了确定 那么发起ajax请求 删除用户
      } else if (result === "confirm") {
        let { data: res } = await this.$http.delete(`users/${id}`);
        if (res.meta.status !== 200) return this.$message.error("删除失败");
        this.$message.success("删除用户成功");
        this.queryInfo.pagenum = 1;
        this.getUserList();
      }
    },
    // 通过用户id查找用户信息
    async getUserById(id) {
      // 让弹出框出现
      this.editDialog = true;
      // 发起ajax请求  回显数据
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户信息失败");
      }
      // 回显数据
      this.editForm = res.data;
      // console.log(this.editForm);
    },
    // 修改信息
    editUserById() {
      this.$refs.editFormRef.validate(async valid => {
        // 如果校验没有通过  那么不能提交
        if (!valid) return;
        // 如果校验通过了 那么就可以提交
        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          this.editForm
        );
        if (res.meta.status !== 200) {
          this.editDialog = false;
          return this.$message.error("用户数据更新失败");
        }
        this.$message.success("用户数据更新成功");
        this.editDialog = false;
        this.getUserList();
      });
    }
  },
  created: function() {
    this.getUserList();
  }
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}
</style>
